package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 上传管理接口
 *
 * @author Haoran Sun
 * @since 2024/08/13
 */

@RestController
@RequestMapping("/api/album")
public class FileUploadApiController {

    @Resource
    private MinioConstantProperties minioConstantProperties;
    @Resource
    private MinioClient minioClient;

    /**
     * 图片上传到minio
     * @param uploadFile 图片文件
     * @return 图片访问路径
     */
    @SneakyThrows
    @PostMapping("/fileUpload")
    //@LoginRequired  前端在这个接口不会传token所以不能加LoginRequired
    public Result<String> fileUpload(@RequestParam("file") MultipartFile uploadFile) {
        if (!minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .build())) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .build());
        }
        // 文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")
                + FilenameUtils.getExtension(uploadFile.getOriginalFilename());
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConstantProperties.getBucketName())
                        .object(fileName)
                        .stream(uploadFile.getInputStream(), uploadFile.getSize(), -1)
                        .contentType(uploadFile.getContentType())
                        .build()
        );
        String url = minioConstantProperties.getEndpointUrl() + "/" + minioConstantProperties.getBucketName() + "/" + fileName;
        return Result.ok(url);
    }


}
